﻿using Microsoft.Xna.Framework;

namespace Engine2D
{
    public class Triangle
    {
        private Vector3 mPosition;
        private Vector3 mNormal;

        public Vector3 A { get; set; }
        public Vector3 B { get; set; }
        public Vector3 C { get; set; }

        public Triangle(Vector3 a, Vector3 b, Vector3 c)
        {
            A = a;
            B = b;
            C = c;
        }

        public float? Intersects(Ray ray, Vector3 position, Matrix rotation, out Vector3? uvw)
        {
            Vector3 wA = Vector3.Transform(A, rotation) + position;
            Vector3 wB = Vector3.Transform(B, rotation) + position;
            Vector3 wC = Vector3.Transform(C, rotation) + position;

            uvw = null;

            Vector3 ab = wB - wA;
            Vector3 ac = wC - wA;

            Vector3 n = Vector3.Cross(ab, ac);
            float d = Vector3.Dot(-ray.Direction, n);
            if (d <= 0.0f)
                return null;

            Vector3 ap = ray.Position - wA;
            float t = Vector3.Dot(ap, n);
            if (t < 0.0f) return null;

            Vector3 e = Vector3.Cross(-ray.Direction, ap);
            float v = Vector3.Dot(ac, e);
            if (v < 0.0f || v > d) return null;
            float w = -Vector3.Dot(ab, e);
            if (w < 0.0f || (v + w) > d) return null;

            float ood = 1.0f / d;
            t *= ood;
            v *= ood;
            w *= ood;
            float u = 1.0f - v - w;

            uvw = new Vector3(u, v, w);
            return t;
        }
    }
}
